package com.dhu.stylefit.controller;

import com.dhu.stylefit.Response;
import com.dhu.stylefit.dao.UserInfo;
import com.dhu.stylefit.service.UserInfoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@RestController
@RequestMapping("/api/user-info")
public class UserInfoController {

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Value("${file.access-path}")
    private String accessPath;

    private static final List<String> ALLOWED_TYPES = Arrays.asList("image/jpeg", "image/png");
    private static final long MAX_FILE_SIZE = 10 * 1024 * 1024;

    private final UserInfoService userInfoService;

    @Autowired
    public UserInfoController(UserInfoService userInfoService) {
        this.userInfoService = userInfoService;
    }


    @GetMapping("/{userId}")
    public Response<UserInfo> getUserInfoById(@PathVariable Integer userId) {
        Optional<UserInfo> userInfo = userInfoService.findById(userId);
        return userInfo.map(Response::newSuccess)
                .orElseGet(() -> Response.newFail("用户不存在"));
    }


    @PutMapping("/{userId}")
    public Response<UserInfo> updateUserInfo(@PathVariable Integer userId, @RequestBody UserInfo userInfo) {
        try {
            userInfo.setUserId(userId);

            UserInfo updatedUser = userInfoService.updateUserInfo(userInfo);
            return Response.newSuccess(updatedUser);
        } catch (Exception e) {
            return Response.newFail("更新用户失败: " + e.getMessage());
        }
    }

    // 上传用户头像
    @PostMapping("/{userId}/avatar")
    public Response<UserInfo> uploadAvatar(
            @PathVariable Integer userId,
            @RequestParam MultipartFile image) {

        try {
            //1. 验证文件
            if (image.isEmpty()) {
                return Response.newFail("请选择要上传的图片");
            }

            // 2. 验证文件类型
            String contentType = image.getContentType();
            if (contentType == null || !ALLOWED_TYPES.contains(contentType)) {
                return Response.newFail("只支持 JPG/PNG 格式的图片");
            }

            // 4. 获取项目根目录
            String projectRoot = System.getProperty("user.dir");
            Path uploadPath = Paths.get(projectRoot, uploadDir).toAbsolutePath().normalize();


            // 3. 验证文件大小
            if (image.getSize() > MAX_FILE_SIZE) {
                return Response.newFail("图片大小不能超过 10MB");
            }

            // 5. 确保目录存在
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 6. 生成唯一文件名
            String originalFilename = image.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFilename = UUID.randomUUID().toString() + fileExtension;

            // 7. 保存文件
            Path filePath = uploadPath.resolve(uniqueFilename);
            Files.copy(image.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);


            // 8. 如果用户已有头像，删除旧文件
            UserInfo existingUser = userInfoService.findById(userId).orElse(null);
            if (existingUser != null && existingUser.getAvatarUrl() != null) {
                String oldFilename = existingUser.getAvatarUrl().replace(accessPath, "");
                Path oldFilePath = uploadPath.resolve(oldFilename);
                Files.deleteIfExists(oldFilePath);
            }
            existingUser.setAvatarUrl(accessPath + uniqueFilename);

            UserInfo updatedUserInfo = userInfoService.updateUserInfo(existingUser);

            return Response.newSuccess(updatedUserInfo);

        } catch (IOException e) {
            e.printStackTrace();
            return Response.newFail("文件上传失败: " + e.getMessage());
        }
    }

    // 上传模特图像
    @PostMapping("/{userId}/model-photo")
    public Response<UserInfo> uploadModelPhoto(
            @PathVariable Integer userId,
            @RequestParam MultipartFile image) {

        try {
            // 1. 验证文件
            if (image.isEmpty()) {
                return Response.newFail("请选择要上传的图片");
            }

            // 2. 验证文件类型
            String contentType = image.getContentType();
            if (contentType == null || !ALLOWED_TYPES.contains(contentType)) {
                return Response.newFail("只支持 JPG/PNG 格式的图片");
            }

            // 3. 验证文件大小
            if (image.getSize() > MAX_FILE_SIZE) {
                return Response.newFail("图片大小不能超过 10MB");
            }

            // 4. 获取项目根目录
            String projectRoot = System.getProperty("user.dir");
            Path uploadPath = Paths.get(projectRoot, uploadDir).toAbsolutePath().normalize();

            // 5. 确保目录存在
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 6. 生成唯一文件名
            String originalFilename = image.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFilename = UUID.randomUUID().toString() + fileExtension;

            // 7. 保存文件
            Path filePath = uploadPath.resolve(uniqueFilename);
            Files.copy(image.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 8. 如果用户已有模特照片，删除旧文件
            UserInfo existingUser = userInfoService.findById(userId).orElse(null);
            if (existingUser == null) {
                return Response.newFail("用户不存在");
            }

            if (existingUser.getModelPhotoUrl() != null) {
                String oldFilename = existingUser.getModelPhotoUrl().replace(accessPath, "");
                Path oldFilePath = uploadPath.resolve(oldFilename);
                Files.deleteIfExists(oldFilePath);
            }

            // 9. 更新用户信息
            existingUser.setModelPhotoUrl(accessPath + uniqueFilename);
            UserInfo updatedUserInfo = userInfoService.updateUserInfo(existingUser);

            return Response.newSuccess(updatedUserInfo);

        } catch (IOException e) {
            e.printStackTrace();
            return Response.newFail("模特照片上传失败: " + e.getMessage());
        }
    }

    // 删除用户头像
    @DeleteMapping("/{userId}/avatar")
    public Response<Void> deleteAvatar(@PathVariable Integer userId) {
        try {
            // 1. 获取用户信息
            UserInfo existingUser = userInfoService.findById(userId).orElse(null);
            if (existingUser == null) {
                return Response.newFail("用户不存在");
            }

            // 2. 检查是否有头像可删除
            if (existingUser.getAvatarUrl() == null) {
                return Response.newFail("用户没有设置头像");
            }

            // 3. 获取项目根目录
            String projectRoot = System.getProperty("user.dir");
            Path uploadPath = Paths.get(projectRoot, uploadDir).toAbsolutePath().normalize();

            // 4. 删除文件
            String oldFilename = existingUser.getAvatarUrl().replace(accessPath, "");
            Path oldFilePath = uploadPath.resolve(oldFilename);
            Files.deleteIfExists(oldFilePath);

            // 5. 清空头像URL
            existingUser.setAvatarUrl(null);
            userInfoService.updateUserInfo(existingUser);

            return Response.newSuccess(null);

        } catch (IOException e) {
            e.printStackTrace();
            return Response.newFail("头像删除失败: " + e.getMessage());
        }
    }

    // 删除模特照片
    @DeleteMapping("/{userId}/model-photo")
    public Response<Void> deleteModelPhoto(@PathVariable Integer userId) {
        try {
            // 1. 获取用户信息
            UserInfo existingUser = userInfoService.findById(userId).orElse(null);
            if (existingUser == null) {
                return Response.newFail("用户不存在");
            }

            // 2. 检查是否有模特照片可删除
            if (existingUser.getModelPhotoUrl() == null) {
                return Response.newFail("用户没有设置模特照片");
            }

            // 3. 获取项目根目录
            String projectRoot = System.getProperty("user.dir");
            Path uploadPath = Paths.get(projectRoot, uploadDir).toAbsolutePath().normalize();

            // 4. 删除文件
            String oldFilename = existingUser.getModelPhotoUrl().replace(accessPath, "");
            Path oldFilePath = uploadPath.resolve(oldFilename);
            Files.deleteIfExists(oldFilePath);

            // 5. 清空模特照片URL
            existingUser.setModelPhotoUrl(null);
            userInfoService.updateUserInfo(existingUser);

            return Response.newSuccess(null);

        } catch (IOException e) {
            e.printStackTrace();
            return Response.newFail("模特照片删除失败: " + e.getMessage());
        }
    }
}
